package root.electronclass.electronclass.ext

import android.content.Context
import android.text.InputFilter
import android.view.MotionEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.core.widget.doAfterTextChanged

/**
 *
 * @author Lokiy
 * @date 2023/2/4 12:50
 */

fun EditText.doOnSearch(callback: (String) -> Boolean) {
    filters = arrayOf<InputFilter>(InputFilter.LengthFilter(20))
    setOnEditorActionListener { v, actionId, event ->
        v ?: return@setOnEditorActionListener false
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            if (event == null || event.action == MotionEvent.ACTION_UP) {
                return@setOnEditorActionListener callback.invoke(v.text.toString()).also {
                    (context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
                        windowToken,
                        InputMethodManager.HIDE_NOT_ALWAYS
                    )
                }
            }
        }
        false
    }
    //添加删除完全刷新逻辑
    var lastText = ""
    doAfterTextChanged {
        if (it.toString().isEmpty() && lastText.isNotEmpty()) {
            callback.invoke("")
        }
        lastText = it.toString()
    }
}